<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class RedCross_Form_Decorator_Time extends Zend_Form_Decorator_Abstract
{

    public function render($content)
    {
        $element = $this->getElement();
        if (!$element instanceof RedCross_Form_Element_Time) {
            return $content;
        }

        $view = $element->getView();
        if (!$view instanceof Zend_View_Interface) {
            // using view helpers, so do nothing if no view present
            return $content;
        }

        $hours   = $element->getHours();
        $minutes = $element->getMinutes();
        $name    = $element->getFullyQualifiedName();

        $hours = $this->fillHours();
        $hourElement = $view->formSelect($name . '[hours]', $element->getHours(), null, $hours);

        $minutes = $this->fillMinutes();
        $minuteElement = $view->formSelect($name . '[minutes]', $element->getMinutes(), null, $minutes);

        $markup = $hourElement . ' : ' . $minuteElement;

        switch ($this->getPlacement()) {
            case self::PREPEND:
                return $markup . $this->getSeparator() . $content;
            case self::APPEND:
            default:
                return $content . $this->getSeparator() . $markup;
        }
    }

    private function fillHours()
    {
        $hours = array();
        
        $hour = 0;
        while($hour <= 23) {
            $longHour = strlen($hour) == 1 ? '0' . $hour : $hour;
            $hours[$longHour] = $longHour;
            $hour++;
        }
        return $hours;
    }

    private function fillMinutes()
    {
        $minutesArray = array();

        $minutes = 0;
        while($minutes <= 55) {
            $longMinutes = strlen($minutes) == 1 ? '0' . $minutes : $minutes;
            $minutesArray[$longMinutes] = $longMinutes;
            $minutes += 5;
        }
        return $minutesArray;
    }
}